package com.cneport.das.server.api;

import com.cneport.das.common.model.param.ClientRequest;
import com.cneport.das.common.model.param.ClientResponse;
import com.cneport.das.common.utils.*;
import com.cneport.das.server.param.dispatch.ParamService;
import com.cneport.das.server.trans.core.AuthCheckService;
import com.cneport.das.server.trans.core.SecurityKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;

/**
 * @Desc 参数服务
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2021-12-07 15:53:06
 */

@RestController
@Slf4j
public class ParamContoller {

    @Autowired
    ParamService paramService;
    @Autowired
    AuthCheckService authCheckService;
    @Autowired
    SecurityKeyService securityKeyService;

    /**
     * 向服务端请求查询参数
     *
     * @param clientReq
     * @return
     */
    @PostMapping("/queryServerParam")
    public String queryParam(@NotNull @RequestBody String clientReq) {
        try {
            clientReq = new String(Base64Utils.decodeFromUrlSafeString(clientReq), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(clientReq);
        ClientRequest request = JAXBUtils.xml2Obj(ClientRequest.class, clientReq);

        boolean bl = SignUtil.check(request);

        ClientRequest.QryReq qryReq = request.getQryReq();
        String guid = qryReq.getGuid();

        if (!bl) {
            return fail(guid, "-1", "签名不正确！");
        }


        String corpNo = qryReq.getCopNo();

        String enctVer = qryReq.getEncoderVer();


        String pubKeyFile = securityKeyService.getKeyFilePath(corpNo, enctVer, null);

        if (StringUtil.isBlank(pubKeyFile)) {
            return fail(guid, "-1", "公钥不存在！");
        }
        try {
            //解密
            request = EncryptUtil.decode(request, pubKeyFile, false);
            ClientRequest.QryReq qryReq1 = request.getQryReq();
            String type = qryReq1.getParaType();
            String qrCode_dec = qryReq1.getParaInfo();
            String copLic = qryReq1.getCopLic();

            boolean isPermit = authCheckService.verify(corpNo, copLic);
            if (!isPermit) {
                return fail(guid, "-1", "未被授权的调用！");
            }

            //调用服务
            String result = paramService.getParam(type, corpNo, qrCode_dec);

            //组装返回值
            return buildRtn(guid, pubKeyFile, result);


        } catch (Exception e) {
            e.printStackTrace();
            return fail(guid, "-1", "请求报文解密失败！");
        }

    }


    private String fail(String guid, String errCode, String errMsg) {
        ClientResponse response = new ClientResponse();
        ClientResponse.QryRetn qryRetn = new ClientResponse.QryRetn();
        qryRetn.setGuid(guid);
        qryRetn.setRespTime(DateUtil.C14());
        qryRetn.setRespCode(errCode);
        qryRetn.setRespInfo(errMsg);
        qryRetn.setSignInfo("");
        response.setQryRetn(qryRetn);
        response.setBizData(new ClientResponse.BizData("JSON", ""));
        return JAXBUtils.obj2Xml(response);
    }


    private String buildRtn(String guid, String pubKey, String data) {
        ClientResponse response = new ClientResponse();

        ClientResponse.QryRetn qryRetn = new ClientResponse.QryRetn();
        qryRetn.setGuid(guid);
        qryRetn.setRespTime(DateUtil.C14());

        ClientResponse.BizData bizData = new ClientResponse.BizData();
        bizData.setData("");

        //-2:服务暂时不支持,-3:转调异常,-4:参数类型未配置，-5:授权未初始化成功，-6：转调地址未被初始化成功，-9：未被授权访问
        if ("-2".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("服务暂时不支持");
        } else if ("-3".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("转调异常");
        } else if ("-4".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("参数类型未配置");
        } else if ("-5".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("授权未初始化成功");
        } else if ("-6".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("转调地址未被初始化成功");
        } else if ("-9".equals(data)) {
            qryRetn.setRespCode("-1");
            qryRetn.setRespInfo("未被授权访问");

        } else {
            qryRetn.setRespCode("0");
            qryRetn.setRespInfo("");
            bizData.setDataForm("JSON");
            bizData.setData(data);
        }

        response.setQryRetn(qryRetn);
        response.setBizData(bizData);
        //加密
        response = EncryptUtil.encode(response, pubKey, false);
        //加签
        response = SignUtil.sign(response);

        return JAXBUtils.obj2Xml(response);
    }
}
